package com.flute.haflute.monitor;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.flute.haflute.jobbox.common.CloudContext;
import com.flute.haflute.tools.PropertiesFileUtil;

public class Cpu {

	private static final Logger LOGGER = LoggerFactory.getLogger(Cpu.class);

	String defaultUnixComand = "cat /proc/cpuinfo";

	private String osName = null;

	public static Cpu cpu = null;

	public Cpu() {
		osName = System.getProperty("os.name").toLowerCase();
	}

	public static Cpu getInstance() {
		if (cpu == null) {
			cpu = new Cpu();
		}
		return cpu;
	}

	/**
	 * 先使用命令行取
	 * 如果取不到在取配置信息，如果配置信息为-1则使用Runtime.getRuntime().availableProcessors();
	 * 
	 * @return
	 */
	public int getTotalCpuCores(int configuredNum) {
		if (osName.contains("windows")) {
			if(configuredNum > 0)
				return configuredNum;
			return getCpuCores();
		} else if (osName.contains("linux") || osName.contains("unix")) {
			int cpucores = getTotalCpuCoresByUnix();
			if (cpucores < 0) {
				cpucores = getCpuCores();
			}
			return cpucores;
		} else {
			LOGGER.error("unknow OS!" + osName);
			return getCpuCores();
		}
	}

	/**
	 * 使用命令集获取CPU内核数量
	 * 
	 * @return
	 */
	private int getTotalCpuCoresByUnix() {
		int cpucores = -1;
		ProcessBuilder builder = new ProcessBuilder(getExecString(getCommand("GETUNIXCPUINFO")));
		try {
			Process process = builder.start();
			BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream()));
			String line;

			while ((line = reader.readLine()) != null) {
				if (line.startsWith("cpu cores")) {
					// String cpucoresAry[] = line.split(":");
					cpucores += 1;// Integer.valueOf(cpucoresAry[1].trim());
				}
			}
			reader.close();
		} catch (IOException e) {
			LOGGER.error("getTotalCpuCoresByUnix error!" + e);
		}
		return cpucores;
	}

	private String getCommand(String comandkey) {
		if (osName.contains("windows")) {
			return null;
		} else if (osName.contains("linux") || osName.contains("unix")) {
			return PropertiesFileUtil.getProperty(PropertiesFileUtil.loadPropertiesFile(CloudContext.getRootDir()
																						+ "conf/command.properties"),
					comandkey, defaultUnixComand);

		} else {
			return comandkey;
		}

	}

	/**
	 * 获取命令集
	 */
	private String[] getExecString(String command) {
		String commands[] = null;
		if (command != null) {
			commands = command.split(" ");
		}
		return commands;
	}

	/**
	 *从配置文件里面取CPU信息
	 * 
	 * @return
	 */
	private int getCpuCores() {
		return Runtime.getRuntime().availableProcessors();
	}

	public static void main(String args[]) {
		int testint = new Cpu().getTotalCpuCores(1);
		System.out.println(" testint = " + testint);
	}
}
